/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.demo.util.impl;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 *
 * @author student
 */

public final class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private String errorPage;
    
    public String getErrorPage() {
        return errorPage;
    }

    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }
    
    private String jsonErrorPage;
    
    public String getJsonErrorPage() {
        return jsonErrorPage;
    }

    public void setJsonErrorPage(String jsonErrorPage) {
        this.jsonErrorPage = jsonErrorPage;
    }

    @Override
    public void handle(HttpServletRequest req, HttpServletResponse res, AccessDeniedException ade) throws IOException, ServletException {
        String page = (isAjax(req) ? getJsonErrorPage() : getErrorPage());
        res.sendRedirect(page);
    }
    
    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
    
}